package com.dongdongshop.mq;

import cn.hutool.core.util.StrUtil;
import com.dongdongshop.pojo.TbOrder;
import com.dongdongshop.pojo.TbUserScoreAccount;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.service.ScoreService;
import com.dongdongshop.vo.OrderNumVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Component
@RocketMQMessageListener(consumerGroup = "my-consumer", topic = "order-score")
public class MQConsumer implements RocketMQListener<OrderNumVO>{

    @Resource
    private ScoreService scoreService;

    @DubboReference()
    private OrderService orderService;

    @Override
    public void onMessage(OrderNumVO orderNumVO) {
        TbUserScoreAccount score = new TbUserScoreAccount();
        TbOrder order = orderService.getOrderNum(orderNumVO.getOrderNum());
        String userId = order.getUserId();
        Long uId = Long.parseLong(userId);
        //判断数据库中有没有这个用户ID
        TbUserScoreAccount scoreAccount = scoreService.selectByUserId(uId);
        score.setUserId(uId.intValue());
        Double payment = Double.parseDouble(order.getPayment().toString());
        if (scoreAccount == null){
            //如果没有就添加
            score.setTotalScore(payment);
            int i = scoreService.addScore(score);
        }else {
            //如果有就根据ID修改当前用户的积分
            score.setId(scoreAccount.getId());
            score.setTotalScore(scoreAccount.getTotalScore()+payment);
            int i = scoreService.updateScore(score);
        }
    }
}
